#include "ObjectManager.h"
#include <cassert>
#include "IEntity.h"

/*static*/ CObjectManager*	CObjectManager::s_Instance = nullptr;

/*static*/ CObjectManager*	CObjectManager::GetInstance( void )
{
	// Dynamically allocate the instance (if needed)
	if( s_Instance == nullptr )
		s_Instance = new CObjectManager;


	// Return the pointer
	return s_Instance;
}

/*static*/ void				CObjectManager::DeleteInstance( void )
{
	delete s_Instance;
	s_Instance = nullptr;
}


CObjectManager::CObjectManager(void)
{
}


CObjectManager::~CObjectManager(void)
{

}

void CObjectManager::AddObject( IEntity* ptr )
{	 
	// Sanity-check
	assert( ptr != nullptr && "CObjectManager::AddObject - cannot send null pointer!" );

	// Add the object to the vector
	m_Objects.push_back( ptr );

	// Increase the reference count
	ptr->AddRef();
}	

void CObjectManager::RemoveObject( IEntity* ptr )
{	 
	// Sanity-check
	assert( ptr != nullptr && "CObjectManager::RemoveObject - cannot send null pointer!" );
	
	// Find & remove the pointer from the vector
	for( OListIterator iter = m_Objects.begin(); iter != m_Objects.end(); ++iter )
	{
		if( (*iter) == ptr )
		{
			iter = m_Objects.erase( iter );

			// Decrease the reference count
			ptr->Release();

			break;
		}
	}

}	

void CObjectManager::RemoveAllObjects( void )
{	 
	// Release each pointer
	for( OListIterator iter = m_Objects.begin(); iter != m_Objects.end(); ++iter )
		(*iter)->Release();

	// Collapse the vector
	m_Objects.clear();
}	 
	 
// Update each game token in the vector
void CObjectManager::UpdateAllObjects( float fElapsedTime )
{	 
	for( OListIterator iter = m_Objects.begin(); iter != m_Objects.end(); ++iter )
		(*iter)->Update(fElapsedTime);
}	 
	 
// Render each game token in the vector
void CObjectManager::RenderAllObjects( void )
{
	for( OListIterator iter = m_Objects.begin(); iter != m_Objects.end(); ++iter )
		(*iter)->Render();
}

void CObjectManager::CheckCollisions( void )
{
	for( OListIterator iter = m_Objects.begin(); iter != m_Objects.end(); ++iter )
	{
		for( OListIterator iter2 = m_Objects.begin(); iter2 != m_Objects.end(); ++iter2 )
			if( (*iter) != (*iter2) )
				if( (*iter)->CheckCollision((*iter2)) )
				{
					continue;
				}
	}
}